import { defineStore } from "pinia";
import { ref } from "vue";
import { getLoginUserUsingGet, userLogoutUsingPost } from "@/api/userController";
import { ResponseCodeEnum, UserRoleEnum } from "@/enums";
import { ElMessage } from "element-plus";

/**
 * 登录用户信息全局状态
 */
export const useLoginUserStore = defineStore("loginUser", () => {
  // 把未登录的状态放在这里, 用于复用
  const notLoginUserValue: API.LoginUserVO = {
    userName: "未登录",
    userRole: UserRoleEnum.NOT_LOGIN,
  };

  // 初始状态则设置为 notLoginUserValue, GlobalHeader 在挂载时会去获取当前登录用户信息
  const loginUser = ref<API.LoginUserVO>(notLoginUserValue);

  /**
   * 获取登录用户信息
   */
  async function fetchLoginUser() {
    const res = await getLoginUserUsingGet();

    if (res.data.code === ResponseCodeEnum.SUCCESS && res.data.data != null) {
      loginUser.value = res.data.data;
    } else {
      loginUser.value = notLoginUserValue;
    }
  }

  /**
   * 登出
   */
  async function logout() {
    // 前端登出
    loginUser.value = notLoginUserValue;
    // 后端登出
    await userLogoutUsingPost();
  }

  return { loginUser, fetchLoginUser, logout };
});
